﻿#include "MemoryByteTest.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

MemoryByteTest::MemoryByteTest()
{

}

void MemoryByteTest::test()
{
    //代表字符'A'；二进制：0100 0001；占一个字节
    unsigned char ch1 = 0x41;

    //二进制：0000 1010；代表16进制的一个数；一字节；不可匹配ASCII码上的字符
    unsigned char ch2 = 0x0A;

    //将数字57(0x39)放入内存，二进制：0011 1001;一字节，直接输出的是字符"9"
    unsigned char ch3 = 57;
    printf("%c\n",ch3);

    //输出ch1的地址，地址占4个字节,不足的填充0
    printf("%08X ,%08X\n",(unsigned int)&ch1,(unsigned int)&ch2);

    //将int型数字3的字面值，即字符'3'，存入char
    int nNum = 3;
    char ch4;
    sprintf((char*)&(ch4),"%d",nNum);
    printf("%c\n",ch4);

    //将int型数字3的字面值，即字符'3'，存入char
    char ch5;
    itoa(nNum,&ch5,10);
    printf("%c\n",ch5);
}

void MemoryByteTest::test2()
{
    long long nData = -922337203685477580;
    //拷贝成字符串
    char arrCharInString[20] = {0};
#ifdef _MSC_VER
    int nRet = sprintf_s(arrCharInString,20,"%lld",nData);
#else
    int nRet = snprintf(arrCharInString,20,"%lld",nData);
#endif
    std::cout<<"copy to string : "<<arrCharInString<<" "<<nRet<<std::endl;

    //内存拷贝
    char arrCharInMemory[8] = {0};
    memcpy(arrCharInMemory,&nData,8);
    std::cout<<"print after mem copy : "<<arrCharInMemory<<std::endl;
    long long nRecvData = 0;
    memcpy(&nRecvData,arrCharInMemory,8);

    std::cout<<"mem return : "<<nRecvData<<std::endl;
}
/**
 *@brief 将字符'A',的字面值作为内存值，即“Ox0A”
          这个跟上例的itoa刚好是一个相反的过程
*/
char MemoryByteTest::ConvertHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
        return ch-0x30;
    else if((ch >= 'A') && (ch <= 'F'))
        return ch-'A'+10;
    else if((ch >= 'a') && (ch <= 'f'))
        return ch-'a'+10;
    else return (-1);
}
/**
 *@brief 以二进制输出一个字符
*/
void MemoryByteTest::BinaryPrint(char ch)
{
    for(int i = 0; i < 8; ++i)
    {
        if(ch << i & 0x80)
            std::cout << '1';
        else
            std::cout << '0';
    }
    std::cout << ' ';
}

int MemoryByteTest::sum(int a)
{
    auto c = 0;
    static int b = 3;
    c+=1;
    b+=2;
    return (a+b+c);
}

void MemoryByteTest::testSum()
{
    int I;
    int a = 2;

    for(I = 0; I < 5; I++)
    {
        printf("%d\n",sum(a));
    }
}
